package com.yhy.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

public class WebUtils {

	//-- header 常量定义 --//
	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;

	public final static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("x-requested-with");
		//		String contentType = request.getContentType();
		// 表明是一个Ajax的post请求，并且不是使用隐藏的iframe实现的
        return "XMLHttpRequest".equalsIgnoreCase(requestedWith);
    }

	public static void render(final HttpServletResponse response, final String contentType, final String content, final String... headers) {
		initResponseHeader(response, contentType, headers);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static void renderText(final HttpServletResponse response, final String text, final String... headers) {
		render(response, "text/plain", text, headers);
	}

	public static void renderHtml(final HttpServletResponse response, final String html, final String... headers) {
		render(response, "text/html", html, headers);
	}

	public static void renderXml(final HttpServletResponse response, final String xml, final String... headers) {
		render(response, "text/xml", xml, headers);
	}

	public static void renderJson(final HttpServletResponse response, final String jsonString, final String... headers) {
		render(response,"application/json", jsonString, headers);
	}

	public static void renderJson(final HttpServletResponse response, final Object data, final String... headers) {
		initResponseHeader(response, "application/json", headers);
		render(response,"application/json", JsonUtils.toJson(data), headers);
	}

	/**
	 * 直接输出支持跨域Mashup的JSONP.
	 *
	 * @param callbackName callback函数名.
	 * @param object Java对象,可以是List<POJO>, POJO[], POJO ,也可以Map名值对, 将被转化为json字符串.
	 */
	public static void renderJsonp(final HttpServletResponse response, final String callbackName, final Object object, final String... headers) {
		String jsonString = JsonUtils.toJson(object);
		String result = new StringBuilder().append(callbackName).append("(").append(jsonString).append(");").toString();
		//渲染Content-Type为javascript的返回内容,输出结果为javascript语句, 如callback197("{html:'Hello World!!!'}");
		render(response, "application/json", result, headers);
	}

	/**
	 * 分析并设置contentType与headers.
	 */
	private static void initResponseHeader(final HttpServletResponse response, final String contentType, final String... headers) {
		//分析headers参数
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName + "非法的header类型");
			}
		}
		//设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			setNoCacheHeader(response);
		}
	}

	/**
	 * 设置禁止客户端缓存的Header.
	 */
	public static void setNoCacheHeader(HttpServletResponse response) {
		//Http 1.0 header
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		//Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
	}

	/**
	 * <br>
	 * <b>功能：</b>获取语言信息<br>
	 * @param request
	 * @return
	 */
	public static Locale getLocal(HttpServletRequest request) {
		return RequestContextUtils.getLocale(request);
	}

	/**
	 * 获取访问的真实ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	
}
